package com.community.process._1010.common.handler;

import com.community.process._1010.common.api.CommonResult;
import com.community.process._1010.common.api.ErrEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class FrameworkGlobalExceptionHandler {

    @ExceptionHandler(FrameworkBusinessRuntimeException.class)
    public CommonResult<String> error(FrameworkBusinessRuntimeException e) {
        Integer code = ErrEnum.SYS_ERR.getErrCode();
        if (e.getErrCode() != null) {
            code = e.getErrCode();
        }
        log.error("错误异常",e);
        return CommonResult.failed(code,e.getErrMsg());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResult<String> error(ConstraintViolationException e) {
        Integer code = ErrEnum.SYS_ERR.getErrCode();
        log.error("ConstraintViolationException错误异常",e);
        return CommonResult.failed(code,e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<String> error(MethodArgumentNotValidException e) {
        Integer code = ErrEnum.SYS_ERR.getErrCode();
        log.error("MethodArgumentNotValidException错误异常",e);
        String message = e.getMessage();
        if (!CollectionUtils.isEmpty(e.getAllErrors())) {
            message = e.getAllErrors().get(0).getDefaultMessage();
        }
        return CommonResult.failed(code,message);
    }

}
